package com.elitel.common.kudu;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.kudu.client.KuduClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

//import org.apache.log4j.LogManager;
//import org.apache.log4j.Logger;

public class KuduClientPoolUtil {
    private final Logger logger = LogManager.getLogger(KuduClientPoolUtil.class);
    private GenericObjectPool<KuduClient> clientPool = null;

    public KuduClientPoolUtil(String masterAddress, long operationTimeoutMs, int maxtotal, int minEvictableIdle, int timeBetweenEviction) {
        // 对象池配置类对象
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

        // 设置池中client最大数量
        poolConfig.setMaxTotal(maxtotal);

        //设置池中对象回收的最小的空闲时间
        poolConfig.setMinEvictableIdleTimeMillis(minEvictableIdle);

        //设置池中对象回收线程扫描的时间间隔，为负数则不开启该线程
        poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEviction);

        // 创建ClientPoolFactory工厂类对象
        KuduClientPoolFactory kuduClientPoolFactory = new KuduClientPoolFactory(masterAddress, operationTimeoutMs);

        //生成对象池
        this.clientPool = new GenericObjectPool<KuduClient>(kuduClientPoolFactory, poolConfig);
    }

    /**
     * 获得对象
     *
     * @return
     */
    public KuduClient getClient() {
        // 从池中获取一个对象
        KuduClient client = null;
        try {
            client = clientPool.borrowObject();
//            logger.info("获取Kudu客户端连接成功");
        } catch (Exception e) {
            logger.error("获取Kudu客户端连接失败");
        }
        return client;
    }

    /**
     * 归还对象
     *
     * @param client
     */
    public void returnClient(KuduClient client) {
//        logger.info("Kudu客户端连接已归还");
        clientPool.returnObject(client);
    }
}
